package com.springboot.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.cx.item.common.exception.ParamsCheckException;
import com.springboot.demo.model.constants.SunMiniappRedisConstants;
import com.springboot.demo.model.model.CustomerLoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Heavin on 2017/11/7.
 * Des
 */
@Slf4j
public abstract class BaseController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    protected CustomerLoginInfo getCurrUserLoginInfo() {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String customerToken = req.getHeader(SunMiniappRedisConstants.CUSTOMER_HEAD_TOKEN_KEY);
        if (StrUtil.isEmpty(customerToken)){
            throw new ParamsCheckException("token验证失败，请重新登录");
        }
        String tokenStr = (String) redisTemplate.opsForHash().get(SunMiniappRedisConstants.CUSTOMER_CACHE_REDIS_TOKEN_KEY, customerToken);
        String customerId = tokenStr.split("_")[0];

        // 登陆信息
        CustomerLoginInfo customerLoginInfo = new CustomerLoginInfo();
        customerLoginInfo.setCustomerId(Integer.parseInt(customerId));
        customerLoginInfo.setCustomerToken(customerToken);

        return customerLoginInfo;
    }

}
